const {
  mock
} = require("mockjs");
let {
  Random
} = require("mockjs");
const Common = require("../common/index");
const dbo = require("../common/database");
class Service extends Common {
  constructor() {
    super("users");
  }

  async add(ctx) {
    try {
      let data = {
        ...ctx.params,
        userId: this.uuid(),
      };
      let res = await dbo.insertOne("users", data);
      ctx.body = this.handleSuccess(res);
    } catch (error) {
      ctx.body = this.handleError(error);
    }
  }

  async getSmsCode(ctx) {
    let {
      phone
    } = ctx.params;
    let reg = /^(13[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|14[0-9])[0-9]{8}$/;
    if (!reg.test(phone)) {
      ctx.body = this.handleError({
        message: "手机号码格式错误",
      });
      return false;
    }

    try {
      let smsCode = Random.integer(1000, 9999);
      let user = await dbo.findOne("users", {
        phone
      });
      if (user) {
        await dbo.updateOne("users", {
          phone
        }, {
          phone,
          smsCode
        });
      } else {
        await dbo.insertOne("users", {
          phone,
          smsCode
        });
      }

      ctx.body = {
        code: 200,
        msg: "验证码已发送,有效时间为2分钟",
        smsCode: smsCode,
      };
    } catch (error) {
      ctx.body = {
        code: 400,
        msg: error.message || "服务器错误",
      }
    }
  }

  async loginBySmsCode(ctx) {
    try {
      let {
        phone,
        smsCode
      } = ctx.params;
      let reg = /^(13[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|14[0-9])[0-9]{8}$/;
      if (!reg.test(phone)) {
        ctx.body = this.handleError({
          message: "手机号码格式错误",
        });
        return false;
      }

      let user = await dbo.findOne('users',{
        phone,
        smsCode
      });

      if (user) {
        let token = this.getToken({
          phone,
          userId: user.userId,
        });
        ctx.body = {
          code: 666,
          msg: "登录成功",
          result: {
            phone,
            token,
            userId: user.userId,
          },
        };
      } else {
        ctx.body = {
          code: 400,
          msg: "验证码不正确",
        };
      }
    } catch (error) {
      ctx.body = {
        code: 400,
        msg: error.message
      }
    }
  }

  async register(ctx) {
    try {
      let {
        phone,
        pwd,
        nickname = ""
      } = ctx.params;
      let reg = /^(13[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|14[0-9])[0-9]{8}$/;
      if (!reg.test(phone)) {
        ctx.body = this.handleError({
          message: "手机号码格式错误",
        });
        return false;
      }
      let userRes = await dbo.findOne("users", {
        phone
      });
      if (userRes) {
        ctx.body = this.handleError({
          message: "手机号码已注册",
        });
        return false;
      }

      let data = {
        phone,
        pwd,
        nickname,
        userId: this.uuid(),
      };
      let res = await dbo.insertOne("users", data);
      delete res.pwd;
      delete res._id;
      ctx.body = this.handleSuccess(res);
    } catch (error) {
      ctx.body = this.handleError(error);
    }
  }

  async list(ctx) {
    let {
      pageSize = 7, currPage = 1
    } = ctx.params;
    delete ctx.params.pageSize;
    delete ctx.params.currPage;
    try {
      let list = await dbo.findListByPage("users", pageSize, currPage, {});
      let total = await dbo.count("users");
      ctx.body = {
        currPage,
        pageSize,
        total,
        code: 200,
        msg: "success",
        data: list,
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: error.message,
      };
    }
  }

  async all(ctx) {
    try {
      let list = await dbo.findList("users", {});
      let total = await dbo.count("users");
      ctx.body = {
        total,
        code: 200,
        msg: "success",
        data: list,
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: error.message,
      };
    }
  }

  async edit(ctx) {
    let {
      userId
    } = ctx.params;
    delete ctx.params.userId;
    ctx.params.updateTime = Date.now();
    try {
      let res = await dbo.updateOne("users", {
        userId
      }, ctx.params);
      ctx.body = this.handleSuccess(res);
    } catch (error) {
      ctx.body = this.handleError(error);
    }
  }

  async detail(ctx) {
    try {
      let user = ctx.user;
      if (!ctx.user.userId) {
        let {
          status,
          msg
        } = user;
        ctx.body = this.handleError({
          message: msg,
          code: 602,
        });
        return false;
      }

      // 用户数据
      let res = await dbo.findOne("users", {
        userId: user.userId
      });
      delete res._id;
      delete res.pwd;

      // 模拟数据
      let assets = mock(/[1-9]{5,8}/) * 1;
      let balance = mock(/[1-9]{3,5}/) * 1;
      let pc = mock(/8|9|10|11|12|13/);
      // 总收益
      let income = assets * pc / 100;
      // 昨日收益
      let lastIncome = (assets * pc / 100 / 365).toFixed(2) * 1;
      let userInfo = {
        assets: assets.toFixed(2),
        balance: balance.toFixed(2),
        income: income.toFixed(2),
        lastIncome: lastIncome.toFixed(2),
      }
      if (!res.assets) {
        dbo.updateOne("users", {
          userId: user.userId
        }, userInfo);
      }
      ctx.body = this.handleSuccess({
        ...userInfo,
        ...res
      });
    } catch (error) {
      ctx.body = this.handleError(error);
    }
  }

  async login(ctx) {
    let {
      phone,
      pwd
    } = ctx.params;
    try {
      let res = await dbo.findOne("users", {
        phone,
        pwd
      });
      if (res) {
        let token = this.getToken({
          userId: res.userId,
        });
        delete res._id;
        delete res.pwd;
        res.token = token;
        ctx.body = this.handleSuccess(res);
      } else {
        ctx.body = this.handleError({
          message: "用户不存在",
          code: 500,
        });
      }
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: error.message,
      };
    }
  }

  async del(ctx) {
    try {
      let res = await dbo.deleteOne("users", ctx.params);
      let msg = res.deletedCount > 0 ? "删除成功" : "删除失败";
      ctx.body = {
        code: 200,
        msg,
        data: res,
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: error.message,
      };
    }
  }
}
module.exports = new Service();